/**
 * 登录页面
 * 仅支持验证码登录
 */
import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  ActivityIndicator,
  Animated,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/Ionicons';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { useNavigation } from '@react-navigation/native';
import { useUser } from '../context/UserContext';
import { userAPI } from '../api';
import { ToastManager } from '../components/Toast';
import { COLORS, SHADOWS } from '../styles/constants';

export default function LoginScreen() {
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();
  const { login } = useUser();

  // 表单数据
  const [phone, setPhone] = useState('');
  const [verificationCode, setVerificationCode] = useState('');

  // UI状态
  const [isLoading, setIsLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);

  // 动画
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(50)).current;

  // 倒计时定时器引用
  const countdownTimer = useRef(null);

  // 进入动画
  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 600,
        useNativeDriver: true,
      }),
      Animated.spring(slideAnim, {
        toValue: 0,
        friction: 8,
        tension: 40,
        useNativeDriver: true,
      }),
    ]).start();

    return () => {
      if (countdownTimer.current) {
        clearInterval(countdownTimer.current);
      }
    };
  }, []);

  /**
   * 验证手机号格式
   * @param {string} phoneNumber - 手机号
   * @returns {boolean} 是否有效
   */
  const validatePhone = phoneNumber => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phoneNumber);
  };

  /**
   * 发送验证码
   * 点击"获取验证码"按钮时调用
   */
  const sendVerificationCode = async () => {
    // 验证手机号
    if (!validatePhone(phone)) {
      ToastManager.warning('请输入正确的手机号');
      return;
    }

    // 倒计时期间不可重复发送
    if (countdown > 0) {
      return;
    }

    try {
      setIsLoading(true);
      // 调用发送验证码API
      const response = await userAPI.sendCode(phone);

      // 打印返回数据用于调试

      // 检查返回数据
      if (response?.data) {
        const { code, msg } = response.data;

        if (code === 200 || code === 0) {
          // 发送成功
          ToastManager.success('验证码已发送，请注意查收');

          // 开始60秒倒计时
          setCountdown(60);
          countdownTimer.current = setInterval(() => {
            setCountdown(prev => {
              if (prev <= 1) {
                clearInterval(countdownTimer.current);
                return 0;
              }
              return prev - 1;
            });
          }, 1000);
        } else if (code === 500) {
          // 服务器错误
          if (
            msg?.includes('频繁') ||
            msg?.includes('次数') ||
            msg?.includes('过多')
          ) {
            ToastManager.error('尝试次数过多，请稍后再试');
          } else if (msg?.includes('失败')) {
            ToastManager.error(msg || '发送失败，请稍后重试');
          } else {
            ToastManager.error(msg || '发送验证码失败，请稍后重试');
          }
        } else {
          // 其他错误
          ToastManager.error(msg || '发送验证码失败，请稍后重试');
        }
      } else {
        // 没有返回数据，假设成功（兼容旧接口）
        ToastManager.success('验证码已发送，请注意查收');

        // 开始60秒倒计时
        setCountdown(60);
        countdownTimer.current = setInterval(() => {
          setCountdown(prev => {
            if (prev <= 1) {
              clearInterval(countdownTimer.current);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      }
    } catch (error) {
      ToastManager.error(error.message || '发送验证码失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 验证码登录
   * 点击"登录"按钮时调用
   */
  const handleLogin = async () => {
    // 验证手机号格式
    if (!validatePhone(phone)) {
      ToastManager.warning('请输入正确的手机号');
      return;
    }

    // 验证验证码（至少4位）
    if (!verificationCode || verificationCode.length < 4) {
      ToastManager.warning('请输入验证码（至少4位）');
      return;
    }

    try {
      setIsLoading(true);

      // 调用验证码登录API
      const response = await userAPI.loginWithCode(phone, verificationCode);

      if (response?.data) {
        // 检查业务状态码
        const { code, msg, data } = response.data;

        if (code === 200 || code === 0) {
          // 登录成功 - 提取access_token和用户信息
          const {
            access_token,
            nickName,
            avatar,
            phone: userPhone,
            hasReg,
            openid,
            scope,
            role,
          } = data || {};

          if (access_token) {
            // 构造用户信息对象
            const userInfo = {
              nickname: nickName,
              avatar: avatar,
              phone: userPhone,
              hasReg: hasReg,
              openid: openid,
              scope: scope,
              role: role,
            };

            // 保存登录状态（token使用access_token）
            await login(access_token, userInfo);
            ToastManager.success('登录成功');

            // 延迟返回，让用户看到成功提示
            setTimeout(() => {
              navigation.goBack();
            }, 1000);
          } else {
            ToastManager.error('登录数据异常，请重试');
          }
        } else if (code === 500 && msg?.includes('验证码')) {
          // 验证码相关错误
          if (msg.includes('失效') || msg.includes('过期')) {
            ToastManager.error('验证码已失效，请重新获取');
            // 清空验证码输入框
            setVerificationCode('');
          } else if (msg.includes('错误') || msg.includes('不正确')) {
            ToastManager.error('验证码错误，请重新输入');
          } else {
            ToastManager.error(msg || '验证码验证失败');
          }
        } else {
          // 其他业务错误
          ToastManager.error(msg || '登录失败，请重试');
        }
      } else {
        ToastManager.error('登录失败，请重试');
      }
    } catch (error) {
      ToastManager.error(error.message || '验证码错误或已过期');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView
        contentContainerStyle={[
          styles.scrollContent,
          { paddingTop: insets.top + 20 },
        ]}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        {/* 顶部装饰圆圈 */}
        <View style={styles.decorationTop}>
          <View style={[styles.circle, styles.circle1]} />
          <View style={[styles.circle, styles.circle2]} />
          <View style={[styles.circle, styles.circle3]} />
        </View>

        {/* 返回按钮 */}
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Icon name="arrow-back" size={24} color="#333" />
        </TouchableOpacity>

        <Animated.View
          style={[
            styles.content,
            {
              opacity: fadeAnim,
              transform: [{ translateY: slideAnim }],
            },
          ]}
        >
          {/* 标题区域 */}
          <View style={styles.headerSection}>
            <View style={styles.logoContainer}>
              <MaterialCommunityIcons
                name="map-marker-radius"
                size={50}
                color="#FF6B6B"
              />
            </View>
            <Text style={styles.title}>欢迎回来</Text>
            <Text style={styles.subtitle}>
              使用手机验证码登录，继续您的旅程
            </Text>
          </View>

          {/* 表单区域 */}
          <View style={styles.formContainer}>
            {/* 手机号输入框 */}
            <View style={styles.inputWrapper}>
              <View style={styles.inputIconWrapper}>
                <Icon name="phone-portrait" size={20} color="#FF6B6B" />
              </View>
              <TextInput
                style={styles.input}
                placeholder="请输入手机号"
                placeholderTextColor="#999"
                value={phone}
                onChangeText={setPhone}
                keyboardType="phone-pad"
                maxLength={11}
                autoCapitalize="none"
              />
              {phone.length > 0 && (
                <TouchableOpacity
                  onPress={() => setPhone('')}
                  style={styles.clearButton}
                >
                  <Icon name="close-circle" size={20} color="#CCC" />
                </TouchableOpacity>
              )}
            </View>

            {/* 验证码输入框 */}
            <View style={styles.inputWrapper}>
              <View style={styles.inputIconWrapper}>
                <Icon name="chatbubble-ellipses" size={20} color="#FF6B6B" />
              </View>
              <TextInput
                style={styles.input}
                placeholder="请输入验证码"
                placeholderTextColor="#999"
                value={verificationCode}
                onChangeText={setVerificationCode}
                keyboardType="number-pad"
                maxLength={8}
              />
              {/* 获取验证码按钮 */}
              <TouchableOpacity
                onPress={sendVerificationCode}
                style={[
                  styles.codeButton,
                  countdown > 0 && styles.codeButtonDisabled,
                ]}
                disabled={countdown > 0 || isLoading}
              >
                {isLoading ? (
                  <ActivityIndicator size="small" color="#FF6B6B" />
                ) : (
                  <Text
                    style={[
                      styles.codeButtonText,
                      countdown > 0 && styles.codeButtonTextDisabled,
                    ]}
                  >
                    {countdown > 0 ? `${countdown}秒` : '获取验证码'}
                  </Text>
                )}
              </TouchableOpacity>
            </View>

            {/* 登录按钮 */}
            <TouchableOpacity
              style={[
                styles.loginButton,
                isLoading && styles.loginButtonDisabled,
              ]}
              onPress={handleLogin}
              disabled={isLoading}
            >
              {isLoading ? (
                <ActivityIndicator size="small" color="#fff" />
              ) : (
                <>
                  <Text style={styles.loginButtonText}>登录</Text>
                  <Icon name="arrow-forward" size={20} color="#fff" />
                </>
              )}
            </TouchableOpacity>
          </View>
        </Animated.View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.secondary,
  },
  scrollContent: {
    flexGrow: 1,
    paddingBottom: 40,
  },
  decorationTop: {
    position: 'absolute',
    top: 0,
    right: 0,
    width: 200,
    height: 200,
  },
  circle: {
    position: 'absolute',
    borderRadius: 999,
    backgroundColor: COLORS.primary,
    opacity: 0.08,
  },
  circle1: {
    width: 100,
    height: 100,
    top: -30,
    right: -20,
  },
  circle2: {
    width: 150,
    height: 150,
    top: 20,
    right: -50,
  },
  circle3: {
    width: 60,
    height: 60,
    top: 80,
    right: 30,
  },
  backButton: {
    position: 'absolute',
    top: 60,
    left: 20,
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: COLORS.background.card,
    justifyContent: 'center',
    alignItems: 'center',
    ...SHADOWS.sm,
    zIndex: 10,
  },
  content: {
    paddingHorizontal: 24,
    paddingTop: 80,
  },
  headerSection: {
    alignItems: 'center',
    marginBottom: 40,
  },
  logoContainer: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: COLORS.primaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 20,
  },
  title: {
    fontSize: 32,
    fontWeight: '800',
    color: COLORS.text.primary,
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 15,
    color: COLORS.text.tertiary,
    textAlign: 'center',
    paddingHorizontal: 20,
  },
  formContainer: {
    marginTop: 40,
    gap: 16,
  },
  inputWrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: COLORS.background.card,
    borderRadius: 16,
    paddingHorizontal: 16,
    height: 56,
    ...SHADOWS.sm,
  },
  inputIconWrapper: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: COLORS.primaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  input: {
    flex: 1,
    fontSize: 16,
    color: COLORS.text.primary,
  },
  clearButton: {
    padding: 4,
  },
  codeButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 8,
    backgroundColor: COLORS.primaryLight,
  },
  codeButtonDisabled: {
    backgroundColor: COLORS.background.secondary,
  },
  codeButtonText: {
    fontSize: 14,
    fontWeight: '600',
    color: COLORS.primary,
  },
  codeButtonTextDisabled: {
    color: COLORS.text.quaternary,
  },
  loginButton: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.primary,
    borderRadius: 16,
    height: 56,
    marginTop: 8,
    gap: 8,
    shadowColor: COLORS.primary,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 4,
  },
  loginButtonDisabled: {
    backgroundColor: COLORS.primarySoft,
    opacity: 0.6,
  },
  loginButtonText: {
    fontSize: 18,
    fontWeight: '700',
    color: COLORS.white,
  },
});
